package com.ly.consumer.thread;


import com.common.core.utils.ThreadPoolUtil;

import java.util.concurrent.*;

//线程池的使用
//步骤
// 1.先创建线程池对象
//2. 创建线程任务 创建runnable接口子类对象
//3.提交线程任务到线程池
class MyRunnablePool implements Runnable{
    @Override
    public void run() {
        method();
    }
    //同步方法处理线程安全问题 只有拿到所资源的那个线程才会执行 执行完了 释放掉锁资源
    public synchronized  void method(){
        System.out.println("我需要一个教练");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("教练来了："+Thread.currentThread().getName());
        System.out.println("教授完毕，教练走了");
    }
}
public class threadPool {

    public static void main1(String[] args) {
        //1.先创建线程池对象
        //创建一个定长的线程池 ，如果线程池里面的线程不够 则等待回收后的线程继续执行任务直到执行完
//        ExecutorService pool =Executors.newFixedThreadPool(3);
        //创建一个可缓存的线程池，如果当前线程池超出了处理需求 则回收线程，如果需求增加会增加线程
//        ExecutorService pool =Executors.newCachedThreadPool();
        //创建一个单线程的线程池 顺序执行 一个一个线程来执行 保证任务有顺序进行
        ExecutorService pool =Executors.newSingleThreadExecutor();
        //2.创建runnable接口子类对象
        MyRunnablePool myThreadPool = new MyRunnablePool();
        //提交线程去线程池
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
//        pool.submit(myThreadPool);
        //线程池 不会自动关闭 一般也不会关闭 终止掉整个程序
//        pool.shutdown();
        //创建一个固定长度的线程池，而且以延时或者定时来执行
        ScheduledExecutorService scheduledExecutorService =Executors.newScheduledThreadPool(3);
        for (int i = 0; i < 3 ; i++) {
            scheduledExecutorService.schedule(myThreadPool,10, TimeUnit.SECONDS);
        }
    }

    public static void main(String[] args) {
        //创建线程池
        ThreadPoolExecutor threadPoolExecutor = ThreadPoolUtil.getThreadPoolExecutorCPU();
        //创建runnable 实现类对象
        MyRunnablePool myThreadPool = new MyRunnablePool();
        threadPoolExecutor.execute(myThreadPool);
        //向线程池提交任务 一个线程一个任务
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
        threadPoolExecutor.submit(myThreadPool);
    }


}
